package com.speedchina.permission.base.typehandler;

import com.speedchina.framework.utils.ApplicationContextHolder;
import com.speedchina.permission.base.typehandler.inter.OperatorService;
import com.speedchina.permission.base.typehandler.model.OperatorModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 操作者 类型处理类
 *
 * @author hank
 * @create 2021-04-15 上午8:32
 **/
@Slf4j
@MappedTypes(OperatorModel.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class OperatorTypeHandler implements TypeHandler<OperatorModel> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, OperatorModel operatorModel, JdbcType jdbcType) {
        // 暂不处理, 若有必要 则 取 operatorModel.getId() 存储即可
    }

    @Override
    public OperatorModel getResult(ResultSet resultSet, int i) throws SQLException {
        String operatorId = resultSet.getString(i);
        return this.translateOperatorModel(operatorId);
    }

    @Override
    public OperatorModel getResult(ResultSet resultSet, String s) throws SQLException {
        String operatorId = resultSet.getString(s);
        return this.translateOperatorModel(operatorId);
    }

    @Override
    public OperatorModel getResult(CallableStatement cs, int i) throws SQLException {
        String operatorId = cs.getString(i);
        return this.translateOperatorModel(operatorId);
    }

    /**
     * 转换 操作id 为操作者对象
     *
     * @param operatorId 操作者ID
     * @return
     */
    private OperatorModel translateOperatorModel(String operatorId) {
        if (StringUtils.isBlank(operatorId)) {
            return null;
        }
        OperatorService operatorService = ApplicationContextHolder.getBean(OperatorService.class);

        return operatorService == null ? null : operatorService.get(operatorId);
    }
}
